//
//  QYSearchViewController.m
//  QingYue
//
//  Created by Zheng on 2017/4/11.
//  Copyright © 2017年 com.lanou.product_A. All rights reserved.
//

#import "QYSearchViewController.h"
#import "QYSearchView.h"
#import "QYSearchCell.h"
#import "QYSearchDetaiViewController.h"

static NSString *kQYSearchCell_ID = @"kQYSearchCell_ID";

#define kRightItemColor RGB(47, 202, 103, 1)
static NSString *const kHotTitle = @"热门搜索";
static NSString *const kRightItemTitle = @"搜索";
static const CGFloat kVerticalSpacing = 22.5f;
static const CGFloat kHorizontalSpacing = 20.f;
static const CGFloat kBtnHeight = 30.f;

@interface QYSearchViewController () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UILabel *hotTitleLbl;
@property (nonatomic, strong) UIView *hotBgView;
@property (nonatomic, strong) QYSearchView *searchView;

@property (nonatomic, strong) NSArray *hotArr;
@property (nonatomic, strong) NSArray *historyArr;

@property (nonatomic, strong) UITableView *myTableView;

@end

@implementation QYSearchViewController

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _historyArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    QYSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:kQYSearchCell_ID];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"QYSearchCell" owner:nil options:nil] lastObject];
    }
    
    cell.nameLbl.text = _historyArr[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    QYSearchDetaiViewController *SearchDetail = [[QYSearchDetaiViewController alloc] init];
    SearchDetail.keyWord = _historyArr[indexPath.row];
    [self.navigationController pushViewController: SearchDetail animated:YES];

}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 30;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    [self subviewsInView];
    
    [self loadHotData];
    
    [self loadHistoryData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar addSubview:self.searchView];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [_searchView removeFromSuperview];
    _searchView = nil;
}

- (void)loadHistoryData {
    NSDictionary *param = @{@"username":[kUserDefaults objectForKey:@"username"]};
    [[YCRequestDataService sharedManager] Post:@"GetHistSearch" parameters:param success:^(id response) {
        if ([response[@"Code"] isEqualToString:@"成功"]) {
            NSArray *conditionList = response[@"conditionList"];
            _historyArr = [conditionList copy];
            [_myTableView reloadData];            
        }
    } failure:^{
        
    }];
    
    
}

#pragma mark -通过数据创建热门标题
- (void)loadHotData {
    
    [[YCRequestDataService sharedManager] Post:@"GetHotSearch" parameters:nil success:^(id response) {
        if ([response[@"Code"] isEqualToString:@"成功"]) {
            NSArray *conditionList = response[@"conditionList"];
            _hotArr = [conditionList copy];
            
            _myTableView.tableFooterView = self.hotBgView;
            
            [_myTableView reloadData];
            
        }
    } failure:^{
        
    }];
}

#pragma mark - 用户点击事件
#pragma mark 导航栏搜索
- (void)rightBarButtonPressed:(UIButton *)sender {
    
    if ([_searchView.searchTfx.text length] > 0) {
        NSLog(@"点击了 %@",_searchView.searchTfx.text);
        QYSearchDetaiViewController *SearchDetail = [[QYSearchDetaiViewController alloc] init];
        SearchDetail.keyWord = _searchView.searchTfx.text;
        [self.navigationController pushViewController: SearchDetail animated:YES];
    }
}

#pragma mark 热门搜索
- (void)searchHotBtnAction:(UIButton *)sender {

    QYSearchDetaiViewController *SearchDetail = [[QYSearchDetaiViewController alloc] init];
    SearchDetail.keyWord = sender.titleLabel.text;
    [self.navigationController pushViewController: SearchDetail animated:YES];
}

#pragma mark - subviews
- (void)subviewsInView {
    
    [self showRightButtonWithTitle:kRightItemTitle titleColor:RGB(47, 202, 103, 1)];

    [self.view addSubview:self.myTableView];
    
    [_myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.equalTo(self.view);
    }];
    
}

- (UITableView *)myTableView {
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
    }
    return _myTableView;
}

- (QYSearchView *)searchView {
    if (!_searchView) {
        _searchView = [[QYSearchView alloc] initWithFrame:CGRectMake(0, 0, 0.68*MSSize_Width, kBtnHeight)];
        _searchView.center = CGPointMake(self.view.center.x, 22);
        _searchView.backgroundColor = RGB(237, 238, 239, 1);
        _searchView.layer.cornerRadius = 5;
        _searchView.layer.masksToBounds = YES;
    }
    return _searchView;
}

- (UILabel *)hotTitleLbl {
    if (!_hotTitleLbl) {
        _hotTitleLbl = [UILabel new];
        _hotTitleLbl.text = kHotTitle;
        _hotTitleLbl.font = Font(15);
    }
    return _hotTitleLbl;
}

- (UIView *)hotBgView {
    if (!_hotBgView) {
        _hotBgView = [[UIView alloc] initWithFrame:(CGRect){0,0,KScreenW,200}];
        _hotBgView.backgroundColor = [UIColor whiteColor];
        [_hotBgView addSubview:self.hotTitleLbl];
        
        [_hotTitleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(kVerticalSpacing);
            make.left.mas_equalTo(kHorizontalSpacing);
        }];
        
        CGFloat kMaxWidth = [UIScreen mainScreen].bounds.size.width-20.f;
        CGFloat kTempWidth = 0;
        NSUInteger kRowNumber = 0;
        CGFloat offSetLeft = 0;
        
        for (int i = 0; i < _hotArr.count; i++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [btn setTitle:_hotArr[i] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            btn.titleLabel.font = Font(12);
            btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            [btn addTarget:self action:@selector(searchHotBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            NSString *titleStr = btn.titleLabel.text;
            NSDictionary *attributeDic = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
            CGFloat btnWidth = [titleStr boundingRectWithSize:CGSizeMake(MAXFLOAT, kBtnHeight) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingUsesFontLeading attributes:attributeDic context:nil].size.width+20;
            
            offSetLeft = kTempWidth;
            kTempWidth += btnWidth;
            
            if (kTempWidth > kMaxWidth) {
                kRowNumber++;
                offSetLeft = 0;
                kTempWidth = btnWidth;
            }
            
            btn.frame = CGRectMake(kHorizontalSpacing+offSetLeft, 55, btnWidth, kBtnHeight);
            
            [_hotBgView addSubview:btn];
        }
        
    }
    return _hotBgView;
}

#pragma mark - 内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
